<template>
  <div class="ele-body">
    <div class="tital_war">
      <h1>商品规格</h1>
    </div>
    <a-card :bordered="false">
      <!-- 表格 -->
      <ele-pro-table ref="table" row-key="id" :datasource="cateLists" :columns="columns" :scroll="{ x: 'max-content' }">
        <template #toolbar>
          <a-space>
            <a-button type="primary" @click="openAddCate()">
              <template #icon>
                <plus-outlined />
              </template>
              <span>添加规格</span>
            </a-button>
          </a-space>
        </template>
        <!-- ID -->
        <template #id="{ record }">
          {{ record.id }}
        </template>
        <!-- 规格名称 -->
        <template #rule_name="{ record }">
          {{ record.rule_name }}
        </template>
        <!-- 规格属性 -->
        <template #rule_attr="{ text: rule_attr}">
          <span v-for="(item, index) in rule_attr" :key="item.id">
            <span>{{ item.attr_name }}</span>
            <span v-if="index + 1 != rule_attr.length">,</span>
          </span>
          <!-- {{ record[0].attr_name }} -->
        </template>
        <!-- 排序 -->
        <template #sort="{ record }">
          {{ record.sort }}
        </template>
        <!-- 操作 -->
        <template #operation="{ record }">
          <div class="editable-row-operations">
            <span> <a @click="editRowIndex(record)">编辑</a>&nbsp; </span>
            <span> <a @click="delRowIndex(record)">删除</a>&nbsp; </span>
          </div>
        </template>
      </ele-pro-table>
    </a-card>
  </div>
  <!-- 编辑弹窗 -->
  <a-modal v-model:visible="editCateDia" title="编辑规格值" @cancel="editHandleCancel" width="70%">
    <template #footer>
      <a-button key="back" @click="editCateOk">确定</a-button>
      <a-button key="submit" type="primary" @click="editHandleCancel">取消</a-button>
    </template>
    <a-form :model="editForm" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="editFormRules" ref="editFromRef">
      <a-form-item label="规格名称中文" name="zh">
        <a-input v-model:value="editForm.zh" placeholder="请输入规格名称中文" />
      </a-form-item>
      <a-form-item label="规格名称英文" name="en">
        <a-input v-model:value="editForm.en" placeholder="请输入规格名称英文" />
      </a-form-item>
      <a-form-item label="规格名称德语" name="de">
        <a-input v-model:value="editForm.de" placeholder="请输入规格名称德语" />
      </a-form-item>
      <a-form-item label="排序">
        <a-input style="width: 100px;" v-model:value="editForm.sort" type="number" :min="0" :max="999" />
      </a-form-item>
    </a-form>
    <a-table :bordered="false" :data-source="editDataSource" :columns="editColumns" row-key="id" :pagination="false" :locale="local">
      <template #zh="{record}">
        <div class="editable-cell-input-wrapper">
          <a-input v-model:value="record.zh" />
        </div>
      </template>
      <template #en="{ record }">
        <div class="editable-cell-input-wrapper">
          <a-input v-model:value="record.en" />
        </div>
      </template>
      <template #de="{ record }">
        <div class="editable-cell-input-wrapper">
          <a-input v-model:value="record.de" />
        </div>
      </template>
      <template #sort="{ record }">
        <div class="editable-cell-input-wrapper">
          <a-input v-model:value="record.sort" :min="0" :max="999" type="number" />
        </div>
      </template>
      <template #operation="{ index }">
        <CloseCircleOutlined :style="{ fontSize: '20px' }" @click="editDelArtt(index)" />
      </template>
    </a-table>
    <a-button type="link" @click="addEditAttr"> <PlusCircleOutlined />添加规格值 </a-button>
  </a-modal>
  <!-- 添加分类弹窗 -->
  <a-modal v-model:visible="addCateDia" title="添加规格值" @cancel="handleCancel" width="70%">
    <template #footer>
      <a-button key="back" @click="addCateOk">确定</a-button>
      <a-button key="submit" type="primary" @click="handleCancel">取消</a-button>
    </template>
    <a-form :model="addForm" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="addFormRules" ref="addFormRef">
      <a-form-item label="规格名称中文" name="cateName_zh">
        <a-input v-model:value="addForm.cateName_zh" placeholder="请输入规格名称中文" />
      </a-form-item>
      <a-form-item label="规格名称英文" name="cateName_en">
        <a-input v-model:value="addForm.cateName_en" placeholder="请输入规格名称英文" />
      </a-form-item>
      <a-form-item label="规格名称德语" name="cateName_de">
        <a-input v-model:value="addForm.cateName_de" placeholder="请输入规格名称德语" />
      </a-form-item>
      <a-form-item label="排序">
        <a-input style="width: 100px;" v-model:value="addForm.sort" type="number" :min="0" :max="999" />
      </a-form-item>
    </a-form>
    <a-table :bordered="false" :data-source="addForm2" :columns="editColumns" row-key="id" :pagination="false" :locale="local">
      <template #zh="{record}">
        <div class="editable-cell-input-wrapper">
          <a-input v-model:value="record.zh" />
        </div>
      </template>
      <template #en="{ record }">
        <div class="editable-cell-input-wrapper">
          <a-input v-model:value="record.en" />
        </div>
      </template>
      <template #de="{ record }">
        <div class="editable-cell-input-wrapper">
          <a-input v-model:value="record.de" />
        </div>
      </template>
      <template #sort="{ record }">
        <div class="editable-cell-input-wrapper">
          <a-input v-model:value="record.sort" :min="0" :max="999" type="number" />
        </div>
      </template>
      <template #operation="{ index }">
        <CloseCircleOutlined :style="{ fontSize: '20px' }" @click="delArtt(index)" />
      </template>
    </a-table>
    <a-button type="link" @click="addAttr"> <PlusCircleOutlined />添加规格值 </a-button>
  </a-modal>
</template>

<script>
import { createVNode } from 'vue'
import qs from 'qs'
import { PlusOutlined, ExclamationCircleOutlined, CloseCircleOutlined, PlusCircleOutlined } from '@ant-design/icons-vue'
import { mapGetters } from 'vuex'

export default {
  name: 'SystemUser',
  components: {
    PlusOutlined,
    CloseCircleOutlined,
    PlusCircleOutlined
  },
  computed: {
    ...mapGetters(['permission'])
  },
  data() {
    return {
      // 商品列表数据
      cateLists: [],
      columns: [
        {
          title: 'ID',
          dataIndex: 'id',
          width: 90
        },
        {
          title: '规格名称',
          dataIndex: 'rule_name'
        },
        {
          title: '规格属性',
          dataIndex: 'rule_attr',
          slots: {
            customRender: 'rule_attr'
          }
        },
        {
          title: '排序',
          dataIndex: 'sort'
        },
        {
          title: '编辑',
          slots: { customRender: 'operation' }
        }
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      // selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      // 分类名称
      searchName: '',
      // 新建分类的对话框
      addCateDia: false,
      // 添加分类数据
      addForm: {
        id: 0,
        cateName_zh: '',
        cateName_en: '',
        cateName_de: '',
        sort: 999
      },
      // 添加规格值的table数据
      addForm2: [],
      // 添加数据的验证
      addFormRules: {
        cateName_zh: [
          {
            required: true,
            message: '内容不能为空',
            trigger: 'blur'
          }
        ],
        cateName_en: [
          {
            required: true,
            message: '内容不能为空',
            trigger: 'blur'
          }
        ],
        cateName_de: [
          {
            required: true,
            message: '内容不能为空',
            trigger: 'blur'
          }
        ]
      },
      // 编辑的弹窗控制
      editCateDia: false,
      // 编辑的form表单数据
      editForm: {},
      editFormRules: {
        zh: [
          {
            required: true,
            message: '内容不能为空',
            trigger: 'blur'
          }
        ],
        en: [
          {
            required: true,
            message: '内容不能为空',
            trigger: 'blur'
          }
        ],
        de: [
          {
            required: true,
            message: '内容不能为空',
            trigger: 'blur'
          }
        ]
      },
      // 编辑的table数据
      editDataSource: [],
      // 编辑弹窗表格
      editColumns: [
        {
          title: '规格值中文',
          dataIndex: 'zh',
          slots: {
            customRender: 'zh'
          }
        },
        {
          title: '规格值英文',
          dataIndex: 'en',
          slots: {
            customRender: 'en'
          }
        },
        {
          title: '规格值德语',
          dataIndex: 'de',
          slots: {
            customRender: 'de'
          }
        },
        {
          title: '排序',
          dataIndex: 'sort',
          slots: {
            customRender: 'sort'
          }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          slots: {
            customRender: 'operation'
          }
        }
      ],
      // 设置添加表格的空状态
      local: { emptyText: <span /> },
      // 添加规格的数据
      addOrderInfo: {}
    }
  },
  created() {
    this.getCateLists()
  },
  methods: {
    // 获取商品列表数据
    /* 修改用户状态 */
    async editStatus(row) {
      console.log(row)
      console.log(typeof row.is_show)
      console.log(row.is_show)
      let flog = null
      if (row.is_show == 0) {
        flog = 1
      } else {
        flog = 0
      }
      const res = await this.$http.post('/product/category/display', qs.stringify({ id: row.id, is_show: flog }))
      console.log(res)
      if (res.status == 200) {
        this.$message.success('切换成功！')
        this.getCateLists()
      }
    },
    /* 分类名称查询 */
    onSearch() {
      console.log(this.findOptions)
      // 清除输入框数据
      this.findOptions = { type: null, is_show: null, name: null }
    },
    // 打开新建弹窗
    async openAddCate() {
      this.addCateDia = true
      // this.getSelectOption();
    },
    // 确认添加分类
    addCateOk() {
      this.$refs.addFormRef
        .validate()
        .then(async () => {
          let sends = {
            'rule_name[zh]': this.addForm.cateName_zh,
            'rule_name[en]': this.addForm.cateName_en,
            'rule_name[de]': this.addForm.cateName_de,
            sort: this.addForm.sort
          }
          for (let i = 0; i < this.addForm2.length; i++) {
            sends[`rule_attr[${i}][id]`] = this.addForm2[i].id
            sends[`rule_attr[${i}][sort]`] = this.addForm2[i].sort
            sends[`rule_attr[${i}][attr_name][zh]`] = this.addForm2[i].zh
            sends[`rule_attr[${i}][attr_name][en]`] = this.addForm2[i].en
            sends[`rule_attr[${i}][attr_name][de]`] = this.addForm2[i].de
          }
          this.addOrderInfo = sends
          const res = await this.$http.post('/product/rule', qs.stringify(sends))
          console.log(res)
          if (res.data.code == 0) {
            this.$message.success('规格添加成功')
            this.addCateDia = false
            this.addForm = {
              id: 0,
              cateName_zh: '',
              cateName_en: '',
              cateName_de: '',
              sort: 999
            }
            this.addForm2 = []
            this.getCateLists()
            this.addCateDia = false
          }
        })
        .catch(error => {
          console.log('error', error)
          this.$message.error('添加失败')
        })
    },
    // 取消添加分类
    handleCancel() {
      this.addForm = {
        id: 0,
        cateName_zh: '',
        cateName_en: '',
        cateName_de: '',
        sort: 999
      }
      this.addForm2 = []
      this.addCateDia = false
      this.$refs.addFormRef.resetFields()
    },
    /* 获取商品分类列表 */
    async getCateLists() {
      const { data: res } = await this.$http.get('/product/rule?lang=en')
      console.log(res)
      this.cateLists = res.data.list
      console.log(this.cateLists)
    },
    // 编辑按钮
    async editRowIndex(row) {
      console.log(row)

      const { data: res } = await this.$http.get('/product/rule/' + row.id)

      this.editForm = res.data.rule_name
      this.editForm.sort = res.data.sort
      this.editForm.id = row.id
      console.log(this.editForm)
      let newarr = []
      res.data.rule_attr.forEach(element => {
        newarr.push({
          id: element.id,
          sort: element.sort,
          zh: element.attr_name.zh,
          en: element.attr_name.en,
          de: element.attr_name.de
        })
      })
      this.editDataSource = newarr
      this.editCateDia = true
    },
    // 删除
    delRowIndex(row) {
      this.$confirm({
        title: '确定删除？',
        content: '删除后将无法恢复',
        okText: '确定',
        cancelText: '取消',
        icon: createVNode(ExclamationCircleOutlined),
        onOk: async () => {
          const res = await this.$http.delete('/product/rule/' + row.id)
          console.log(res)
          if (res.status == 200) {
            this.$message.success('规格删除成功')
            this.getCateLists()
          }
        },
        onCancel: () => {
          this.$message.info('取消操作')
        }
      })
    },
    // 编辑弹窗关闭的回调
    editHandleCancel() {
      this.editCateDia = false
    },
    // 编辑弹窗确定的回调
    async editCateOk() {
      let editArr = {}
      console.log(this.editForm)
      editArr.id = this.editForm.id
      editArr.rule_name = {
        zh: this.editForm.zh,
        en: this.editForm.en,
        de: this.editForm.de
      }

      editArr.sort = this.editForm.sort
      editArr.rule_attr = []
      // for (let i = 0; i < this.editDataSource.length; i++) {
      //   editArr.rule_attr.push({
      //     id: this.editDataSource[i].id
      //   })

      // }
      this.editDataSource.forEach(item => {
        editArr.rule_attr.push({
          id: item.id,
          sort: item.sort,
          attr_name: {
            zh: item.zh,
            en: item.en,
            de: item.de
          }
        })
      })
      console.log(this.editDataSource)
      // if (this.editDataSource.length == 0) {
      //   this.$message.info('请添加规格值')
      //   editArr = {}
      //   editArr.id = this.editForm.id
      //   editArr['rule_name[zh]'] = this.editForm.zh
      //   editArr['rule_name[en]'] = this.editForm.en
      //   editArr['rule_name[de]'] = this.editForm.en
      //   editArr['sort'] = this.editForm.sort
      //   this.editDataSource = []
      //   return
      // }

      const res = await this.$http.post('/product/rule/update', qs.stringify(editArr))
      if (res.data.code != 0) return this.$message.error('编辑失败')
      this.$message.success('编辑成功')
      this.getCateLists()
      this.editCateDia = false
    },
    // 删除规格值
    delArtt(id) {
      console.log(id)
      this.addForm2.splice(id, 1)
      // console.log(this.editDataSource)
    },
    // 编辑的删除
    editDelArtt(id) {
      this.editDataSource.splice(id, 1)
      console.log(this.editDataSource)
    },
    // 添加规格值 -- 规格添加
    addAttr() {
      this.addForm2.push({
        id: 0,
        sort: 999,
        zh: '',
        en: '',
        de: ''
      })
    },
    // 添加规格值 -- 规格编辑
    addEditAttr() {
      this.editDataSource.push({
        id: 0,
        sort: 999,
        zh: '',
        en: '',
        de: ''
      })
    }
  }
}
</script>

<style scoped lang="less">
.ele-body {
  height: 100%;
}
.tital_war {
  width: 100%;
  height: 50px;
  background: #fff;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  h1 {
    margin: 0;
    padding: 0;
    margin-left: 10px;
    font-size: 22px;
    font-weight: 500;
  }
}
</style>
